<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import http from '../http.js'

const chartRef = ref<HTMLElement | null>(null)

onMounted(async () => {
  // 1. 请求数据
  const res = await http.get('/hot.json')
  // 2. 找到女装-外套-children
  const women = res.find((item: any) => item.name === '女装')
  const coat = women.children.find((item: any) => item.name === '外套')
  const data = coat.children.map((item: any) => ({
    value: item.value,
    name: item.name
  }))

  // 3. 组装 option
  const option = {
    title: {
      text: '| 热销商品的占比',
      textStyle: {
        color: '#fff',
        fontSize: 14,
        fontWeight: 'normal'
      },
      left: '2%',
      top: '2%'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      orient: 'horizontal',
      top: '2%',
      right: '2%',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#fff',
        fontSize: 12
      }
    },
    series: [
      {
        name: '商品占比',
        type: 'pie',
        radius: '60%',
        center: ['50%', '55%'],
        data,
        label: {
          show: true,
          formatter: '{b}:{c}',
          color: '#fff',
          fontSize: 14
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  // 4. 渲染图表
  const myChart = echarts.init(chartRef.value!)
  myChart.setOption(option)
  window.addEventListener('resize', () => myChart.resize())
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  padding: 10px;
}
</style>
